package com.example.demo.util;

import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

public class HttpUtil {
  public static String setHttpRequest(String httpUrl, Map<String, String> params) throws Exception {
    //1.定义需要访问的地址
    URL url = new URL(httpUrl);
    //2.连接URl
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    //3.设置请求方式
    httpURLConnection.setRequestMethod("POST");
    //4.携带参数
    httpURLConnection.setDoOutput(true);
    if (params != null && params.size() > 0) {
      StringBuilder sb = new StringBuilder();
      for (Map.Entry<String, String> param : params.entrySet()) {
        sb.append("&").append(param.getKey()).append("=").append(param.getValue());
      }
      httpURLConnection.getOutputStream().write(sb.substring(1).toString().getBytes("UTF-8"));
    }
    //5.发起请求
    httpURLConnection.connect();
    //6.接受返回值
    String response = StreamUtils.copyToString(httpURLConnection.getInputStream(), Charset.forName("UTF-8"));
    return response;
  }

  public static void sendRequest(String httpURL, String jsessionId) throws Exception {
    //1.建立url连接对象
    URL url = new URL(httpURL);
    //2.创建连接
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    //3.设置请求方式
    connection.setRequestMethod("POST");
    //4.设置需要输出
    connection.setDoOutput(true);
    connection.addRequestProperty("Cookie","JSESSIONID="+jsessionId);
    //5.发送请求到服务端
    connection.connect();
    connection.getInputStream();
    connection.disconnect();
  }
}
